<template>
  <div class="app-container">
    <!-- 树形结构菜单 -->
    <splitpanes
      :horizontal="this.$store.getters.device === 'mobile'"
      class="default-theme"
      style="height: 100vh"
    >
      <pane size="10">
        <div class="head-container">
          <el-input
            v-model="projectName"
            placeholder="请输入培训项目"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px; width: 70%"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="projectOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </pane>
    </splitpanes>

    <el-col :span="20">
      <!-- 搜索栏 -->
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入姓名"
            clearable
          />
        </el-form-item>

        <el-form-item label="发票类型" prop="invoiceType">
          <el-select
            v-model="queryParams.invoiceType"
            placeholder="请选择发票类型"
            clearable
          >
            <el-option
              v-for="dict in dict.type.invoice_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发票信息" prop="invoiceInfo">
          <el-input
            v-model="queryParams.invoiceInfo"
            placeholder="请输入发票信息"
            clearable
          />
        </el-form-item>

        <el-form-item label="开票时间" prop="preIssueTime">
          <el-date-picker
            v-model="queryParams.preIssueTime"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            clearable
            style="width: 215px"
          />
        </el-form-item>

        <el-form-item label="证件编号" prop="idNumber">
          <el-input
            v-model="queryParams.idNumber"
            placeholder="请输入证件编号"
            clearable
          />
        </el-form-item>

        <el-form-item label="单位名称" prop="unitName">
          <el-input
            v-model="queryParams.unitName"
            placeholder="请输入单位名称"
            clearable
          />
        </el-form-item>

        <el-form-item label="手机号码" prop="phonenumber">
          <el-input
            v-model="queryParams.phonenumber"
            placeholder="请输入手机号码"
            clearable
          />
        </el-form-item>

        <el-form-item label="费用金额" prop="feeAmount">
          <el-input
            v-model="queryParams.feeAmount"
            placeholder="请输入费用金额"
            clearable
          />
        </el-form-item>

        <el-form-item label="预开状态" prop="invoiceStatus">
          <el-select
            v-model="queryParams.invoiceStatus"
            placeholder="选择预开状态"
            clearable
          >
            <el-option
              v-for="dict in dict.type.invoice_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="报名来源" prop="registrationMethod">
          <el-select
            v-model="queryParams.registrationMethod"
            placeholder="选择报名来源"
            clearable
          >
            <el-option
              v-for="dict in dict.type.registration_method"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="报名时间" prop="registrationTime">
          <el-date-picker
            v-model="queryParams.registrationTime"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            clearable
            style="width: 215px"
          />
        </el-form-item>

        <el-form-item label="缴费状态" prop="paymentStatus">
          <el-select
            v-model="queryParams.paymentStatus"
            placeholder="选择缴费状态"
            clearable
          >
            <el-option
              v-for="dict in dict.type.payment_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>

      <!-- 操作按钮栏 -->
      <el-row :gutter="20" class="mb8">
        <!-- 发票列表 -->
        <el-col :span="12">
          <el-button-group>
            <el-button type="primary">发票列表</el-button>
            <el-button type="primary" plain @click="handleExport"
              >导出</el-button
            >
          </el-button-group>
        </el-col>
        <!-- 刷新 -->
        <el-col :span="12">
          <el-button-group class="button-group-right">
            <el-button type="primary" plain @click="toggleSearch"
              >隐藏搜索</el-button
            >
            <el-button type="primary" plain @click="refreshTable"
              >刷新</el-button
            >
            <el-button type="primary" plain @click="toggleSort"
              >隐藏/排序列</el-button
            >
          </el-button-group>
        </el-col>
        <!-- 预开票操作 -->
        <el-col :span="24" style="margin-top: 10px">
          <el-button-group>
            <el-button type="primary">预开票</el-button>
            <el-button
              type="primary"
              plain
              @click="handleEditInvoiceInfo"
              :disabled="single"
              >编辑开票信息</el-button
            >
            <el-button type="primary" plain @click="handleIssueInvoice"
              >预开票</el-button
            >
            <el-button type="primary" plain @click="handleDownloadInvoice"
              >下载发票</el-button
            >
            <el-button type="primary" plain @click="handleSendInvoice"
              >短信发送发票</el-button
            >
            <el-button type="primary" plain @click="handleRemark"
              >备注</el-button
            >
          </el-button-group>
        </el-col>

        <!-- 退换票操作 -->
        <el-col :span="24" style="margin-top: 10px">
          <el-button-group>
            <el-button type="primary">退换票</el-button>
            <el-button type="primary" plain @click="handleViewExchangeApply"
              >查看退换票申请</el-button
            >
            <el-button type="primary" plain @click="handleAgreeExchange"
              >同意退换票</el-button
            >
            <el-button type="primary" plain @click="handleStartExchange"
              >发起退换票</el-button
            >
            <el-button type="primary" plain @click="handleCancelExchange"
              >取消退换票</el-button
            >
          </el-button-group>
        </el-col>
      </el-row>

      <el-table
        v-loading="loading"
        :data="invoiceList"
        @selection-change="handleSelectionChange"
      >
        <!-- 多选列 -->
        <el-table-column type="selection" width="55" align="center" />

        <!-- 是否办结 -->
        <el-table-column label="是否办结" align="center" prop="isSettled">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.is_settled"
              :value="scope.row.isSettled"
            />
          </template>
        </el-table-column>

        <!-- 缴费状态 -->
        <el-table-column label="缴费状态" align="center" prop="paymentState">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.payment_status"
              :value="scope.row.paymentState"
            />
          </template>
        </el-table-column>

        <!-- 发票状态 -->
        <el-table-column label="发票状态" align="center" prop="invoiceStatus">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.invoice_status"
              :value="scope.row.invoiceStatus"
            />
          </template>
        </el-table-column>

        <!-- 缴费方式 -->
        <el-table-column label="缴费方式" align="center" prop="paymentMethod">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.payment_method"
              :value="scope.row.paymentMethod"
            />
          </template>
        </el-table-column>

        <!-- 诺诺单号 -->
        <el-table-column label="诺诺单号" align="center" prop="nuonuoNumber" />

        <!-- 发票种类 -->
        <el-table-column label="发票种类" align="center" prop="invoiceCategory">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.invoice_category"
              :value="scope.row.invoiceCategory"
            />
          </template>
        </el-table-column>

        <!-- 发票类型 -->
        <el-table-column label="发票类型" align="center" prop="invoiceType">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.invoice_type"
              :value="scope.row.invoiceType"
            />
          </template>
        </el-table-column>

        <!-- 姓名 -->
        <el-table-column label="姓名" align="center" prop="studentName" />

        <!-- 证件编号 -->
        <el-table-column label="证件编号" align="center" prop="idNumber" />

        <!-- 电话 -->
        <el-table-column label="电话" align="center" prop="phonenumber" />

        <!-- 单位名称 -->
        <el-table-column label="单位名称" align="center" prop="unitName" />

        <!-- 单位统一信用代码 -->
        <el-table-column
          label="单位统一信用代码"
          align="center"
          prop="socialCreditCode"
        />

        <!-- 报名来源 -->
        <el-table-column
          label="报名来源"
          align="center"
          prop="registrationMethod"
        >
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.registration_method"
              :value="scope.row.registrationMethod"
            />
          </template>
        </el-table-column>

        <!-- 联系人 -->
        <el-table-column label="联系人" align="center" prop="contact" />

        <!-- 联系人电话 -->
        <el-table-column
          label="联系人电话"
          align="center"
          prop="unitPhonenumber"
        />

        <!-- 培训类型 -->
        <el-table-column label="培训类型" align="center" prop="trainingType" />

        <!-- 培训项目 -->
        <el-table-column label="培训项目" align="center" prop="projectMap" />

        <!-- 教学班 -->
        <el-table-column label="教学班" align="center" prop="trainingClass" />

        <!-- 培训类型（新训/复训） -->
        <el-table-column label="培训类型" align="center" prop="trainingType"
          ><template slot-scope="scope">
            <dict-tag
              :options="dict.type.training_type"
              :value="scope.row.trainingType"
            />
          </template>
        </el-table-column>

        <!-- 培训费 -->
        <!-- <el-table-column label="费用" align="center" prop="projectSum" /> -->
        <el-table-column label="费用" align="center" prop="paymentAmount" />

        <!-- 退费 -->
        <el-table-column label="退费" align="center" prop="refundAmount" />

        <!-- 缴费时间 -->
        <el-table-column label="缴费时间" align="center" prop="paymentTime">
          <template slot-scope="scope">
            <span>{{
              parseTime(scope.row.paymentTime, "{y}-{m}-{d} {h}:{i}:{s}")
            }}</span>
          </template>
        </el-table-column>

        <!-- 上传缴费凭证时间 -->
        <el-table-column
          label="上传缴费凭证时间"
          align="center"
          prop="voucherUploadTime"
        >
          <template slot-scope="scope">
            <span>{{
              parseTime(scope.row.voucherUploadTime, "{y}-{m}-{d} {h}:{i}:{s}")
            }}</span>
          </template>
        </el-table-column>

        <!-- 报名时间 -->
        <el-table-column label="报名时间" align="center" prop="createTime">
          <template slot-scope="scope">
            <span>{{
              parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}")
            }}</span>
          </template>
        </el-table-column>

        <!-- 备注 -->
        <el-table-column label="备注" align="center" prop="remarks" />

        <!-- 操作列 -->
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          fixed="right"
          width="180px"
        >
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleView(scope.row)"
              >查看</el-button
            >

            <el-button
              size="mini"
              type="text"
              @click="handleIssueInvoice(scope.row)"
              >开票</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleExchange(scope.row)"
              >退换票</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleEditInvoiceInfo(scope.row)"
              >开票信息</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 按钮组件 -->
      <EditInvoiceInfoDialog
        :visible="showEditInvoiceInfo"
        :formData="invoiceFormData"
        :dict="dictCache"
        @submit="handleInvoiceSubmit"
        @close="handleEditInvoiceClose"
      ></EditInvoiceInfoDialog>
      <IssueInvoiceDialog
        :visible="showIssueInvoice"
        :count="selectedCount"
        @confirm="handleInvoiceConfirm"
        @close="handleIssueInvoiceClose"
      ></IssueInvoiceDialog>
      <DownloadInvoiceDialog
        :visible="showDownloadInvoice"
        :count="downloadCount"
        @confirm="handleDownloadConfirm"
        @close="handleDownloadClose"
      ></DownloadInvoiceDialog>
      <SendInvoiceSMSDialog
        :visible="showSendInvoiceSMS"
        :count="smsCount"
        @confirm="handleSendInvoiceConfirm"
        @close="handleSendInvoiceSMSClose"
      ></SendInvoiceSMSDialog>
      <PaymentRemarks
        :visible="showRemark"
        :title="`缴费单 ${currentPaymentId} `"
        :business-id="1"
        :initial-remark="defaultRemark"
        :max-length="300"
        @submit="handleRemarkSubmit"
        @close="handleRemarkClose"
      ></PaymentRemarks>
      <ExchangeApplyDialog
        :visible="showViewExchangeApply"
        :formData="exchangeApplyFormData"
        :dict="dictCache"
        @submit="handleViewExchangeApplySubmit"
        @close="handleViewExchangeApplyClose"
      ></ExchangeApplyDialog>
      <AgreeExchangeDialog
        :visible="showAgreeExchange"
        :applicant-name="applicantName"
        @confirm="handleAgreeExchangeConfirm"
        @close="handleAgreeExchangeClose"
      ></AgreeExchangeDialog>
      <CancelExchangeDialog
        :visible="showCancelExchange"
        :exchange-info="exchangeInfo"
        :dict="dictCache"
        @confirm="handleCancelExchangeConfirm"
        @close="handleCancelExchangeClose"
      ></CancelExchangeDialog>
      <StartExchangeDialog
        :visible="showStartExchange"
        :exchange-info="startExchangeInfo"
        :dict="dictCache"
        @submit="handleStartExchangeSubmit"
        @close="handleStartExchangeClose"
      ></StartExchangeDialog>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改发票信息对话框 -->
      <el-dialog
        :title="title"
        :visible.sync="open"
        width="500px"
        append-to-body
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="缴费记录ID" prop="paymentRecordId">
            <el-input
              v-model="form.paymentRecordId"
              placeholder="请输入缴费记录ID"
            />
          </el-form-item>
          <el-form-item label="发票种类" prop="invoiceCategory">
            <el-select
              v-model="form.invoiceCategory"
              placeholder="请选择发票种类"
            >
              <el-option
                v-for="dict in dict.type.invoice_category"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发票类型" prop="invoiceType">
            <el-select v-model="form.invoiceType" placeholder="请选择发票类型">
              <el-option
                v-for="dict in dict.type.invoice_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发票状态" prop="invoiceStatus">
            <el-select
              v-model="form.invoiceStatus"
              placeholder="请选择发票状态"
            >
              <el-option
                v-for="dict in dict.type.invoice_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发票抬头" prop="invoiceTitle">
            <el-input
              v-model="form.invoiceTitle"
              placeholder="请输入发票抬头"
            />
          </el-form-item>
          <el-form-item label="发票编号" prop="invoiceNumber">
            <el-input
              v-model="form.invoiceNumber"
              placeholder="请输入发票编号"
            />
          </el-form-item>
          <el-form-item label="发票金额" prop="invoiceAmount">
            <el-input
              v-model="form.invoiceAmount"
              placeholder="请输入发票金额"
            />
          </el-form-item>
          <el-form-item label="退换票原因" prop="refundReason">
            <el-input
              v-model="form.refundReason"
              placeholder="请输入退换票原因"
            />
          </el-form-item>
          <el-form-item label="退换票金额" prop="refundAmount">
            <el-input
              v-model="form.refundAmount"
              placeholder="请输入退换票金额"
            />
          </el-form-item>
          <el-form-item label="开票时间" prop="issueTime">
            <el-date-picker
              clearable
              v-model="form.issueTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择开票时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="发票信息" prop="invoiceImage">
            <image-upload v-model="form.invoiceImage" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </el-col>
  </div>
</template>

<script>
import {
  listInvoice,
  getInvoice,
  delInvoice,
  addInvoice,
  updateInvoice,
  getInvoiceRefundInfo,
} from "@/api/payment/invoice";
import { paymentRecordList } from "@/api/payment/payment";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import { projectTreeSelect } from "@/api/training/projects";
// 编辑开票信息
import EditInvoiceInfoDialog from "@/components/Payment/EditInvoiceInfoDialog.vue";
// 开发票
import IssueInvoiceDialog from "@/components/Payment/IssueInvoiceDialog.vue";
//下载发票
import DownloadInvoiceDialog from "@/components/Payment/DownloadInvoiceDialog.vue";
//短信发送发票
import SendInvoiceSMSDialog from "@/components/Payment/SendInvoiceSMSDialog.vue";
// 备注
import PaymentRemarks from "@/components/Payment/PaymentRemarksDialog.vue";
//退换票申请
import ExchangeApplyDialog from "@/components/Payment/ExchangeApplyDialog.vue";
//  同意退换票
import AgreeExchangeDialog from "@/components/Payment/AgreeExchangeDialog.vue";
//取消退换票
import CancelExchangeDialog from "@/components/Invoice/CancelExchangeDialog.vue";
//发起退换票
import StartExchangeDialog from "@/components/Invoice/StartExchangeDialog.vue";

export default {
  name: "Invoice",
  dicts: [
    "invoice_category",
    "invoice_status",
    "invoice_type",
    "payment_status",
    "payment_method",
    "is_settled",
    "registration_method",
    "training_type",
  ],
  components: {
    Splitpanes,
    Pane,
    EditInvoiceInfoDialog,
    IssueInvoiceDialog,
    DownloadInvoiceDialog,
    SendInvoiceSMSDialog,
    PaymentRemarks,
    ExchangeApplyDialog,
    AgreeExchangeDialog,
    CancelExchangeDialog,
    StartExchangeDialog,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 发票信息表格数据
      invoiceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        invoiceCategory: null,
        invoiceType: null,
        invoiceStatus: null,
        invoiceTitle: null,
        invoiceNumber: null,
        issueTime: null,
        //新增
        name: null,
        idNumber: null,
        unitName: null,
        phonenumber: null,
        feeAmount: null,
        invoiceInfo: null,
        registrationMethod: null,
        registrationTime: null,
        paymentStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      //新增定义
      // 所有部门树选项
      projectOptions: null,
      //树形结构数据
      projectName: "",
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 编辑开票信息
      showEditInvoiceInfo: false,
      invoiceFormData: {
        invoiceType: "",
        invoiceCategory: "",
        invoiceUnitName: "",
        invoiceCreditCode: "",
      },
      // 预开发票
      showIssueInvoice: false,
      selectedCount: 0,
      //下载发票
      showDownloadInvoice: false,
      downloadCount: 0,
      //短信发送发票
      showSendInvoiceSMS: false,
      smsCount: 0,
      //备注
      showRemark: false,
      currentPaymentId: null,
      defaultRemark: "",
      //退换票申请
      showViewExchangeApply: false,
      exchangeApplyFormData: {
        invoiceStatus: "",
        invoiceCategory: "",
        invoiceType: "",
        name: "",
        unitName: "",
        idNumber: "",
        phonenumber: "",
        applyTime: "",
        applicant: "",
        registrationCategory: "",
        trainingClass: "",
        projectSum: "",
        exchangeAmount: "",
        exchangeReason: "",
        // auditStatus: "通过",
        remarks: "",
        invoiceRefundTime: "",
        invoiceRefundPerson: "",
      },
      //同意退换票
      showAgreeExchange: false,
      applicantName: "",
      //取消退换票
      showCancelExchange: false,
      exchangeInfo: {
        invoiceCategory: "",
        invoiceType: "",
        name: "",
        idNumber: "",
        unitName: "",
        socialCreditCode: "",
        phonenumber: "",
        invoiceAmount: "",
        invoiceNumber: "",
        exchangeReason: "",
      },
      //发起退换票
      showStartExchange: false,
      startExchangeInfo: {
        invoiceCategory: "",
        invoiceType: "",
        name: "",
        idNumber: "",
        unitName: "",
        socialCreditCode: "",
        phonenumber: "",
        invoiceAmount: "",
        invoiceNumber: "",
        exchangeReason: "",
      },
      // 缓存字典数据
      dictCache: {
        payment_method: {},
        is_settled: {},
        payment_status: {},
        invoice_status: {},
        invoice_type: {},
        invoice_category: {},
        registration_method: {},
        training_type: {},
      },
    };
  },
  created() {
    this.getList();
    this.getProjectTree();
    this.$nextTick(async () => {
      await this.loadDicts();
    });
  },
  methods: {
    async loadDicts() {
      this.dictCache.payment_method = this.dict.label.payment_method;
      this.dictCache.is_settled = this.dict.label.is_settled;
      this.dictCache.payment_status = this.dict.label.payment_status;
      this.dictCache.invoice_status = this.dict.label.invoice_status;
      this.dictCache.invoice_type = this.dict.label.invoice_type;
      this.dictCache.invoice_category = this.dict.label.invoice_category;
      this.dictCache.registration_method = this.dict.label.registration_method;
      this.dictCache.training_type = this.dict.label.training_type;
    },
    /** 查询发票信息列表 */
    getList() {
      this.loading = true;

      paymentRecordList(this.queryParams).then((response) => {
        this.invoiceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });

      // listInvoice(this.queryParams).then((response) => {
      //   this.invoiceList = response.rows;
      //   this.total = response.total;
      //   this.loading = false;
      // });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        invoiceId: null,
        paymentRecordId: null,
        invoiceCategory: null,
        invoiceType: null,
        invoiceStatus: null,
        invoiceTitle: null,
        invoiceNumber: null,
        invoiceAmount: null,
        refundReason: null,
        refundAmount: null,
        issueTime: null,
        invoiceImage: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        exampleOne: null,
        exampleTwo: null,
        exampleThree: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.invoiceId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加发票信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const invoiceId = row.invoiceId || this.ids;
      getInvoice(invoiceId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改发票信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.invoiceId != null) {
            updateInvoice(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInvoice(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const invoiceIds = row.invoiceId || this.ids;
      this.$modal
        .confirm('是否确认删除发票信息编号为"' + invoiceIds + '"的数据项？')
        .then(function () {
          return delInvoice(invoiceIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "training/invoice/export",
        {
          ...this.queryParams,
        },
        `invoice_${new Date().getTime()}.xlsx`
      );
    },
    // 新增方法
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.projectId = data.id;
      this.queryParams.pageNum = 1;
      this.getList(this.queryParams);
    },
    // 树节点过滤方法
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 获取树形数据
    getProjectTree(val) {
      var params = { projectName: val };
      params.projectId = this.queryParams.projectId;
      projectTreeSelect(params).then((response) => {
        this.projectOptions = response.data;
        this.enabledProjectOptions = this.filterDisabledDept(
          JSON.parse(JSON.stringify(response.data))
        );
      });
    },
    // 新增方法：下载发票
    handleDownloadInvoice() {
      this.$modal
        .confirm("是否确认下载发票？")
        .then(() => {
          // 实现下载发票的逻辑
          this.$message.success("下载成功");
        })
        .catch(() => {});
    },

    // 新增方法：短信发送发票
    handleSendInvoice() {
      this.$modal
        .confirm("是否确认发送发票短信？")
        .then(() => {
          // 实现发送发票短信的逻辑
          this.$message.success("发送成功");
        })
        .catch(() => {});
    },

    //编辑开票信息
    // 编辑开票信息关闭处理
    handleEditInvoiceClose() {
      this.showEditInvoiceInfo = false;
    },
    // 编辑开票相关方法
    handleInvoiceSubmit(formData) {
      console.log("编辑开票信息提交：", formData);
      const selectedRow =
        this.currentSelectedRow ||
        this.invoiceList.find((item) => item.invoiceId === this.ids[0]);
      console.log("当前行数据：", selectedRow);

      var data = {
        invoiceId: selectedRow.invoiceId,
        invoiceUnitName: formData.invoiceUnitName,
        invoiceCreditCode: formData.invoiceCreditCode,
        invoiceType: formData.invoiceType,
        invoiceCategory: formData.invoiceCategory,
      };
      updateInvoice(data).then(() => {
        this.$modal.msgSuccess("开票信息已更新");
        this.showEditInvoiceInfo = false;
        this.getList(); // 刷新列表
      });
    },

    // 编辑开票相关方法
    handleEditInvoiceInfo(row) {
      // 实现编辑开票信息逻辑

      // // 如果传入了行数据，则使用该行数据；否则查找选中的数据
      // if (row) {
      //   this.currentSelectedRow = row;
      // }
      const selectedRow =
        row && row.invoiceId
          ? row // 如果row存在且有invoiceId属性，则使用row
          : this.invoiceList.find(
              // 否则从列表中查找
              (item) => item.invoiceId === this.ids[0]
            );
      this.currentSelectedRow = selectedRow;
      console.log("编辑开票信息：", selectedRow);
      if (selectedRow) {
        // 设置表单数据
        this.invoiceFormData = {
          invoiceType: selectedRow.invoiceType || "",
          invoiceCategory: selectedRow.invoiceCategory || "",
          invoiceUnitName: selectedRow.invoiceUnitName || "",
          invoiceCreditCode: selectedRow.invoiceCreditCode || "",
        };
        // 显示对话框
        this.showEditInvoiceInfo = true;
      } else {
        // 如果没有选中任何记录，初始化为空数据
        this.invoiceFormData = {
          invoiceUnitName: "",
          invoiceCreditCode: "",
          invoiceType: "1",
          invoiceCategory: "1",
        };
        this.showEditInvoiceInfo = true;
      }
    },
    //预开票
    handleIssueInvoice(row) {
      // 实现开发票逻辑

      // 如果是单个记录，count为1
      if (row) {
        this.selectedCount = 1;
      } else {
        // 如果是多选，获取选中的数量
        if (!row && this.ids.length === 0) {
          this.$message.warning("请至少选择一条数据进行预开票操作");
          return;
        }

        this.selectedCount = this.ids.length;
      }

      // 显示对话框
      this.showIssueInvoice = true;
    },
    handleInvoiceConfirm(count) {
      // 这里可以添加开发票的逻辑
      console.log(`准备对${count}条记录开发票`);
      this.$message.success("发票已生成");
      this.showIssueInvoice = false;
      this.getList(); // 刷新列表
    },
    // 开发票关闭处理
    handleIssueInvoiceClose() {
      this.showIssueInvoice = false;
    },
    //处理下载发票按钮点击
    handleDownloadInvoice() {
      // 获取选中的记录数量
      const count = this.ids.length || 1;

      // 设置下载数量
      this.downloadCount = count;

      // 显示下载确认对话框
      this.showDownloadInvoice = true;
    },

    // 处理下载确认
    handleDownloadConfirm(count) {
      // 这里可以添加实际的下载逻辑
      console.log(`准备下载 ${count} 张发票`);

      // 模拟下载成功
      this.$message.success("发票下载成功");

      // 关闭对话框
      this.handleDownloadClose();
    },

    // 处理下载关闭
    handleDownloadClose() {
      this.showDownloadInvoice = false;
    },

    // 新增方法：处理短信发送发票按钮点击
    handleSendInvoice() {
      // 获取选中的记录数量
      const count = this.ids.length || 1;

      // 设置短信发送数量
      this.smsCount = count;

      // 显示短信发送确认对话框
      this.showSendInvoiceSMS = true;
    },

    // 处理短信发送确认
    handleSendInvoiceConfirm(count) {
      // 这里可以添加实际的短信发送逻辑
      console.log(`准备通过短信发送 ${count} 张发票`);

      // 模拟发送成功
      this.$message.success("发票已通过短信发送");

      // 关闭对话框
      this.handleSendInvoiceSMSClose();
    },

    // 处理短信发送关闭
    handleSendInvoiceSMSClose() {
      this.showSendInvoiceSMS = false;
    },
    //备注
    handleRemark() {
      if (this.ids.length === 0) {
        this.$message.warning("请先选择一条数据");
        return;
      }

      // 实现缴费备注逻辑
      if (this.ids.length === 1) {
        // 使用正确的字段名 preInvoiceId
        const selectedRow = this.invoiceList.find(
          (item) => item.invoiceId === this.ids[0]
        );

        if (selectedRow) {
          this.currentPaymentId = this.ids[0];
          this.defaultRemark = selectedRow.remark || "";
        } else {
          this.currentPaymentId = null;
          this.defaultRemark = "";
        }
      } else {
        this.currentPaymentId = null;
        this.defaultRemark = "";
      }

      this.showRemark = true;
    },
    handleRemarkSubmit(data) {
      // 处理备注提交逻辑
      console.log("备注提交数据:", data);
      // 这里应该调用后端API保存备注信息
      // saveRemark(data).then(() => {
      //   this.$message.success("备注保存成功");
      //   this.showRemark = false;
      //   this.getList(); // 刷新列表
      // }).catch(error => {
      //   this.$message.error("备注保存失败: " + error.message);
      // });

      // 临时处理
      this.$message.success("备注已保存");
      this.showRemark = false;
    },
    handleRemarkClose() {
      this.showRemark = false;
    },
    // 查看退换票申请
    handleViewExchangeApply() {
      // 获取选中的记录
      const selectedRow = this.invoiceList.find(
        (item) => item.invoiceId === this.ids[0]
      );

      if (selectedRow) {
        var params = {
          invoiceId: selectedRow.invoiceId,
          registrationId: selectedRow.registrationId,
        };
        getInvoiceRefundInfo(params).then((res) => {
          // 设置表单数据
          this.exchangeApplyFormData = {
            ...res.data,
            invoiceStatus: "4",
            remark: "",
          };

          console.log("退换票申请信息:", this.exchangeApplyFormData);

          // 显示对话框
          this.showViewExchangeApply = true;
        });
      } else {
        this.$message.warning("请先选择一条记录");
      }
    },
    // 关闭查看退换票申请对话框
    handleViewExchangeApplyClose() {
      this.showViewExchangeApply = false;
    },
    // 提交退换票申请审核
    handleViewExchangeApplySubmit(data) {
      console.log("提交的退换票申请审核数据:", data);

      var params = {
        invoiceId: data.invoiceId,
        registrationId: data.registrationId,
        invoiceStatus: data.invoiceStatus,
        invoiceRefundRemark: data.exchangeReason,
      };
      updateInvoice(params).then(() => {
        this.$message.success("退换票申请已提交");
        this.handleViewExchangeApplyClose();
        this.getList(); // 刷新列表
      });
    },
    // 查看退换票申请
    handleView(row) {
      // 使用传入的行数据或者选中的数据
      const selectedRow =
        row || this.invoiceList.find((item) => item.invoiceId === this.ids[0]);

      if (selectedRow) {
        var params = {
          invoiceId: selectedRow.invoiceId,
          registrationId: selectedRow.registrationId,
        };
        getInvoiceRefundInfo(params).then((res) => {
          // 设置表单数据
          this.exchangeApplyFormData = {
            ...res.data,
            invoiceStatus: "4",
            remark: "",
          };

          console.log("退换票申请信息:", this.exchangeApplyFormData);

          // 显示对话框
          this.showViewExchangeApply = true;
        });
      } else {
        this.$message.warning("请先选择一条记录");
      }
    },
    handleExchange(row) {
      // 使用传入的行数据或者选中的数据
      const selectedRow =
        row || this.invoiceList.find((item) => item.invoiceId === this.ids[0]);

      if (selectedRow) {
        var params = {
          invoiceId: selectedRow.invoiceId,
          registrationId: selectedRow.registrationId,
        };
        getInvoiceRefundInfo(params).then((res) => {
          // 设置表单数据
          this.startExchangeInfo = {
            ...res.data,
            exchangeReason: "",
          };

          console.log("退换票申请信息:", this.startExchangeInfo);

          // 显示对话框
          this.showStartExchange = true;
        });
      } else {
        this.$message.warning("请先选择一条记录");
      }
    },
    //同意退换票
    handleAgreeExchange() {
      // 获取选中的记录
      const selectedRow = this.invoiceList.find(
        (item) => item.invoiceId === this.ids[0]
      );

      if (selectedRow) {
        // 设置申请人姓名
        this.applicantName = selectedRow.studentName || "未知";

        // 显示对话框
        this.showAgreeExchange = true;
      } else {
        this.$message.warning("请先选择一条记录");
      }
    },
    // 关闭同意退换票对话框
    handleAgreeExchangeClose() {
      this.showAgreeExchange = false;
    },
    // 确认同意退换票
    handleAgreeExchangeConfirm() {
      const selectedRow = this.invoiceList.find(
        (item) => item.invoiceId === this.ids[0]
      );
      updateInvoice({
        invoiceId: selectedRow.invoiceId,
        registrationId: selectedRow.registrationId,
        invoiceStatus: "4",
      }).then(() => {
        // 模拟成功
        this.$message.success("退费申请已同意");
        // 关闭对话框
        this.handleAgreeExchangeClose();
        // 刷新列表
        this.getList();
      });
    },
    //取消退换票
    handleCancelExchange() {
      // 获取选中的记录
      const selectedRow = this.invoiceList.find(
        (item) => item.invoiceId === this.ids[0]
      );

      if (selectedRow) {
        var params = {
          invoiceId: selectedRow.invoiceId,
          registrationId: selectedRow.registrationId,
        };
        getInvoiceRefundInfo(params).then((res) => {
          // 设置表单数据
          this.exchangeInfo = {
            ...res.data,
          };

          // 显示对话框
          this.showCancelExchange = true;
        });
      } else {
        this.$message.warning("请先选择一条记录");
      }
    },
    // 关闭取消退换票对话框
    handleCancelExchangeClose() {
      this.showCancelExchange = false;
    },
    // 确认取消退换票
    handleCancelExchangeConfirm() {
      // 这里可以添加实际的取消逻辑
      console.log("已取消退换票申请");
      const selectedRow = this.invoiceList.find(
        (item) => item.invoiceId === this.ids[0]
      );
      var params = {
        invoiceId: data.invoiceId,
        registrationId: selectedRow.registrationId,
        invoiceStatus: "取消退换票",
      };

      updateInvoice(params).then(() => {
        this.$message.success("退换票申请已取消");
        this.handleCancelExchangeClose();
        this.getList(); // 刷新列表
      });
    },
    // 发起退换票按钮点击事件
    handleStartExchange() {
      // 获取选中的记录
      const selectedRow = this.invoiceList.find(
        (item) => item.invoiceId === this.ids[0]
      );

      if (selectedRow) {
        var params = {
          invoiceId: selectedRow.invoiceId,
          registrationId: selectedRow.registrationId,
        };
        getInvoiceRefundInfo(params).then((res) => {
          // 设置表单数据
          this.startExchangeInfo = {
            ...res.data,
            exchangeReason: "",
          };

          console.log("退换票申请信息:", this.startExchangeInfo);
        });

        // 显示对话框
        this.showStartExchange = true;
      } else {
        this.$message.warning("请先选择一条记录");
      }
    },

    // 处理发起退换票提交
    handleStartExchangeSubmit(data) {
      console.log("发起退换票申请数据:", data);

      const selectedRow = this.invoiceList.find(
        (item) => item.invoiceId === this.ids[0]
      );
      var params = {
        invoiceId: data.invoiceId,
        registrationId: selectedRow.registrationId,
        invoiceRefundReason: data.exchangeReason,
        invoiceStatus: "3",
      };

      updateInvoice(params).then(() => {
        this.$message.success("退换票申请已提交");
        this.handleStartExchangeClose();
        this.getList(); // 刷新列表
      });
    },

    // 处理发起退换票关闭
    handleStartExchangeClose() {
      this.showStartExchange = false;
    },
    //刷新按钮组
    toggleSearch() {
      this.showSearch = !this.showSearch;
    },
    refreshTable() {
      this.getList();
    },
    toggleSort() {
      // 实现排序列切换逻辑
    },
  },
  watch: {
    // 根据名称筛选部门树
    projectName(val) {
      this.$refs.tree.filter(val);
      this.getProjectTree(val);
    },
  },
};
</script>
<style scoped>
.app-container {
  display: flex;
}
.el-col {
  height: 100%;
}
.custom-tree-node {
  display: flex;
  align-items: center;
  gap: 4px;
}
/* 按钮组容器样式 */
.button-groups-container {
  margin-bottom: 20px;
}

/* 每行按钮组的间距 */
.button-group-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}

/* 最后一行不显示底部边框 */
.button-group-row:last-child {
  margin-bottom: 0;
  border-bottom: none;
}

/* 按钮组样式 */
.button-group {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

/* 按钮样式调整 */
.button-group .el-button {
  min-width: 80px;
  padding: 6px 12px;
}

/* 刷新按钮组样式 */
.button-group-right {
  float: right;
  margin-right: 50px;
}
</style>
